package com.maven.plugins;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.util.regex.Pattern;

@Mojo(name = "countFile")
public class JavaFileNumPlugin extends AbstractMojo {

    @Parameter(property = "path")
    private String path;

    private static int num = 0;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("url:" + path);
        File file = new File(path);
        if (!file.exists()) {
            getLog().info(path + "：该路径不存在！");
            return;
        }
        countFile(file);
        getLog().info("fileNum:" + num);
    }

    private void countFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                countFile(f);
            }
        } else {
            if (match(file.getName())) {
                getLog().info(file.getName());
                num++;
            }

        }
    }

    private boolean match(String fileName) {
        String regex = "^.+\\.java$";
        Pattern pattern = Pattern.compile(regex);
        return pattern.matcher(fileName).matches();
    }

}
